//
//  SSEmoticonPackage.swift
//  表情包数据
//
//  Created by 叶竞泽 on 2017/2/3.
//  Copyright © 2017年 JingZe. All rights reserved.
//

import UIKit

class SSEmoticonPackage: NSObject {
    
    /// 表情包的分组名
    var groupName: String?
    
    /// 背景图片名字
    var bgImageName: String?
    
    /// 表情包目录, 从目录下加载info.plist可以创建表情模型数组
    var directory: String? {
        
        didSet {
            // 当设置目录时,从目录下加载info.plist
            guard let directory = directory, let path = Bundle.main.path(forResource: "HMEmoticon.bundle", ofType: nil), let bundle = Bundle(path: path), let infoPath = bundle.path(forResource: "info.plist", ofType: nil, inDirectory: directory), let array = NSArray(contentsOfFile: infoPath), let models = NSArray.yy_modelArray(with: SSEmoticon.self, json: array) as? [SSEmoticon] else {
                return
            }
            
            // 遍历models数组,设置每一个表情的目录
            for emoticon in models {
                emoticon.directory = directory
            }
            
            // 设置表情模型数组
            emoticons += models
        }
    }

    /// 表情包数组
    lazy var emoticons = [SSEmoticon]()
    
    var numberOfPages: Int {
        return (emoticons.count - 1) / 20 + 1
    }
    
    /// 从懒加载中按照page截取最多20个表情
    ///
    /// - Parameter page: 第几页
    /// - Returns: 表情数组
    /// 例如有26个表情
    /// page = 0,返回0-19
    /// page = 1,返回20-25
    func emoticons(page: Int) -> [SSEmoticon]? {
        
        // 截取数组的子数组
        
        // 每一页Cell的表情数量
        let count = 20
        
        let location = page * count
        var lenght = count
        
        // 判断数组是否越界
        if location + lenght > emoticons.count {
            lenght = emoticons.count - location
        }
        
        let range = NSRange(location: location, length: lenght)
        let subemoticons = (emoticons as NSArray).subarray(with: range)
        
        return subemoticons as? [SSEmoticon]
    }
    
    override var description: String {
        return yy_modelDescription()
    }
}
